/*
 * Copyright (C) 2009 Anatoly Zenkov
 *
 * This software is provided 'as-is', without any express or implied
 * warranty.  In no event will the author be held liable for any damages
 * arising from the use of this software.
 *
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it
 * freely, subject to the following restrictions:
 *
 * 1. The origin of this software must not be misrepresented; you must not
 *    claim that you wrote the original software. If you use this software
 *    in a product, an acknowledgment in the product documentation would be
 *    appreciated but is not required.
 * 2. Altered source versions must be plainly marked as such, and must not be
 *    misrepresented as being the original software.
 * 3. This notice may not be removed or altered from any source distribution.
 */
package com.kartoshka.utils {
	import flash.geom.Point;

	/**
	 * @author Anatoly Zenkov
	 */
	public class GeomUtil {
		static public function segmentSegmentIntersectionPoint (p0:Point, p1:Point, p2:Point, p3:Point):Point
		{
			var d:Number = (p3.y - p2.y)*(p1.x - p0.x) - (p3.x - p2.x)*(p1.y - p0.y);
			if (!d) return null;
			var u0:Number = ((p3.x - p2.x)*(p0.y - p2.y) - (p3.y - p2.y)*(p0.x - p2.x))/d;
			var u1:Number = ((p1.x - p0.x)*(p0.y - p2.y) - (p1.y - p0.y)*(p0.x - p2.x))/d;
			if (u0 < 0 || u0 > 1 || u1 < 0 || u1 > 1) return null;
			return new Point(p0.x + u0*(p1.x - p0.x), p0.y + u0*(p1.y - p0.y));
		}
		
		static public function lineLineIntersectionPoint (p0:Point, p1:Point, p2:Point, p3:Point):Point
		{
			var d:Number = (p3.y - p2.y)*(p1.x - p0.x) - (p3.x - p2.x)*(p1.y - p0.y);
			if (!d) return null;
			var u0:Number = ((p3.x - p2.x)*(p0.y - p2.y) - (p3.y - p2.y)*(p0.x - p2.x))/d;
			return new Point(p0.x + u0*(p1.x - p0.x), p0.y + u0*(p1.y - p0.y));
		}
	}
}
